package edu.swust.graduation_project.eauction.activity

import android.content.DialogInterface
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Looper
import android.widget.ListView
import android.widget.SearchView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContentProviderCompat.requireContext
import edu.swust.graduation_project.eauction.Adapter.ItemListAdapter
import edu.swust.graduation_project.eauction.Bean.ItemBean
import edu.swust.graduation_project.eauction.R
import edu.swust.graduation_project.eauction.fragment.ItemFragment
import java.sql.Connection
import java.sql.DriverManager
import java.sql.SQLException

class MyBidedActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my_bided)
        var list: ArrayList<ItemBean> = MysqlTobean()
        var searchResult = ArrayList<ItemBean>(list)
        val mLvBided = findViewById<ListView>(R.id.lv_mybided_item)
        val mSvBided = findViewById<SearchView>(R.id.sv_mybided_item)
        val myAdapter = ItemListAdapter(this, searchResult)
        mLvBided.adapter = myAdapter

        mLvBided?.setOnItemClickListener { _, view, i, l ->
            val intent = Intent(this, ItemActivity::class.java)
            intent.putExtra("itemName", searchResult[i].itemName)
            intent.putExtra("itemCreateTime", searchResult[i].itemCreateTime)
            intent.putExtra("itemEndTime", searchResult[i].itemEndTime)
            intent.putExtra("itemPrice", searchResult[i].itemPrice)
            intent.putExtra("itemCreater", searchResult[i].itemCreater)
            intent.putExtra("itemLastBid", searchResult[i].itemLastBid)
            intent.putExtra("itemStartingPrice", searchResult[i].itemStartingPrice)
            intent.putExtra("itemIsDelivery",searchResult[i].itemIsDelivery)
            startActivity(intent)
        }

        mLvBided?.setOnItemLongClickListener { adapterView, view, i, l ->
            val mSharedPreferences: SharedPreferences =
                this.getSharedPreferences(
                    "user",
                    AppCompatActivity.MODE_PRIVATE
                )
            if (searchResult[i].itemCreater == mSharedPreferences.getString("username", "")
                || mSharedPreferences.getString("username", "") == "root"
            ) {
                AlertDialog.Builder(this).setTitle("删除？")
                    .setPositiveButton("删除", DialogInterface.OnClickListener { _, _ ->
                        MysqlDelete(searchResult[i].itemCreateTime.toString().replace(".0", ""))
                    })
                    .setNeutralButton("取消", null).create().show()

            } else {
                Toast.makeText(this, "非创建用户无法操作", Toast.LENGTH_SHORT).show()
            }
            false
        }


        mSvBided?.isIconifiedByDefault = false
        mSvBided?.isSubmitButtonEnabled = true
        mSvBided?.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                searchResult.clear()
                for (value in list) {
                    if (value.itemName.contains(newText!!)) {
                        searchResult.add(value)
                    }
                }
                myAdapter.notifyDataSetChanged()
                return true
            }
        }
        )
    }


    private fun MysqlTobean(): ArrayList<ItemBean> {
        var itemBeanList = ArrayList<ItemBean>()
        val mSharedPreferences: SharedPreferences =
            this.getSharedPreferences(
                "user",
                AppCompatActivity.MODE_PRIVATE
            )
        val userName = mSharedPreferences.getString("username", "")
        val thread = Thread {
            try {
                val sqlSelect = "SELECT * FROM `Item`"
                val cn: Connection = DriverManager.getConnection(
                    "*",
                    "*", "*"
                )
                val ps = cn.createStatement()
                val resultSet = ps!!.executeQuery(sqlSelect)
                if (resultSet != null) {
                    while (resultSet.next()) {
                        val itemName = resultSet.getString("item_name")
                        val itemPrice = resultSet.getFloat("item_price")
                        val itemCreater = resultSet.getString("item_create_user")
                        val itemCreateTime = resultSet.getTimestamp("item_create_time")
                        val itemEndTime = resultSet.getTimestamp("item_end_time")
                        val itemLastBid = resultSet.getString("item_last_bid")
                        val itemStartingPrice = resultSet.getFloat("item_starting_price")
                        val itemIsDelivery=resultSet.getBoolean("item_is_delivery")
                        when (intent.getIntExtra("flag", 1)) {
                            //我参加的拍卖
                            1 -> {
                                if (itemLastBid == userName && itemCreater != userName) {
                                    itemBeanList.add(
                                        ItemBean(
                                            itemName,
                                            itemPrice,
                                            itemCreater,
                                            itemCreateTime,
                                            itemEndTime,
                                            itemLastBid,
                                            itemStartingPrice,
                                            itemIsDelivery
                                        )
                                    )
                                }
                            }
                            //我发起的拍卖
                            2 -> {
                                if (itemCreater == userName) {
                                    itemBeanList.add(
                                        ItemBean(
                                            itemName,
                                            itemPrice,
                                            itemCreater,
                                            itemCreateTime,
                                            itemEndTime,
                                            itemLastBid,
                                            itemStartingPrice,
                                            itemIsDelivery
                                        )
                                    )
                                }
                            }
                        }

                    }
                }
                cn.close()
                ps.close()
                resultSet.close()
            } catch (e: ClassNotFoundException) {
                e.printStackTrace()
            } catch (e: SQLException) {
                e.printStackTrace()
            }
        }
        thread.start()
        thread.join()
        if (itemBeanList.isEmpty()) Thread.sleep(10)
        return itemBeanList
    }


    private fun MysqlDelete(createTime: String) {
        object : Thread() {
            override fun run() {
                super.run()
                try {
                    val sqlSelete = "DELETE FROM `test_case`.`Item` WHERE `Item`." +
                            "`item_create_time` = '$createTime'"
                    val cn: Connection = DriverManager.getConnection(
                        "*",
                        "*", "*"
                    )
                    val ps = cn.createStatement()
                    ps.execute(sqlSelete)
                    cn.close()
                    ps.close()
                    Looper.prepare()
                    Toast.makeText(this@MyBidedActivity, "删除成功", Toast.LENGTH_SHORT).show()
                    startActivity(intent)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }.start()
    }

}